package com.leyou.item.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.Jshop.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> queryBrandsByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        //使用通用Mapper
        //Example为通用查询对象
        Example example = new Example(Brand.class);
        //Criteria支持模糊查询
        Example.Criteria criteria = example.createCriteria();

        //根据name模糊查询，或者根据首字母模糊查询
        if(StringUtils.isNotBlank(key)){
            criteria.andLike("name", "%" + key + "%").orEqualTo("letter", key);
        }

        //添加分页条件
        //第几页 每一页的记录数
        PageHelper.startPage(page,rows);

        //添加排序条件
        if (StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy + " " + (desc? "desc" : "asc"));
        }

        List<Brand> brands = this.brandMapper.selectByExample(example);

        //包装成pageInfo
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        //包装成分页结果集返回
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());

    }

    //不仅要新增品牌，还要维护品牌和商品分类的中间表，这两个数据库操作要有事务特性
    @Transactional
    public void saveBrand(Brand brand, List<Long> cids){
        //新增品牌
        //选择性保存 （保存一个实体，null的属性不会保存，会使用数据库默认值）
        //在Brand中已经实现主键自增
        this.brandMapper.insertSelective(brand);

        //新增中间表数据
        cids.forEach(cid -> {
            this.brandMapper.insertBrandAndCateGory(cid,brand.getId());
        });
    }

    //根据分类id查询所有品牌
    public List<Brand> queryBrandsByCid(Long cid){
        return this.brandMapper.selectBrandByCid(cid);
    }


    //根据品牌查id
    public Brand queryBrandById(Long id) {
        return brandMapper.selectByPrimaryKey(id);
    }


}
